using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.IO;

namespace UDPActiveMonitor
{

   public partial class Form1 : Form
   {
      int cnt;
      private ReadMessagesWorker thRead,thReadSync,thReadVin;
      Msg MessService,MessSync,MessVin;
      int MaxLines;
      int TrimLines;
      public Form1()
      {
         InitializeComponent();
         MaxLines = 500;
         TrimLines = 250;
         cnt = 0;
         MessVin = new Msg();
         MessVin.mtype = Msg.MessageType.vin;
         MessService = new Msg();
         MessService.mtype = Msg.MessageType.service;
         MessSync = new Msg();
         MessSync.mtype = Msg.MessageType.sync;
      }
      //private Queue<Msg> messQ;
      private List<Msg> messServiceL;
      private List<Msg> messSyncL;
      private List<Msg> messVinL;
      private void Form1_Load(object sender, EventArgs e)
      {
         //timer1.Interval = 10;
         //timer1.Enabled = true;
         //timer1.Start();

         thRead = new ReadMessagesWorker();
         thRead.WorkerSupportsCancellation = true;
         thRead.WorkerReportsProgress = true;
         thRead.ProgressChanged += new System.ComponentModel.ProgressChangedEventHandler(this.thRead_ProgressChanged);
         thRead.RunWorkerAsync(MessService);

         thReadSync = new ReadMessagesWorker();
         thReadSync.WorkerSupportsCancellation = true;
         thReadSync.WorkerReportsProgress = true;
         thReadSync.ProgressChanged += new System.ComponentModel.ProgressChangedEventHandler(this.thRead_ProgressChanged);
         thReadSync.RunWorkerAsync(MessSync);

         thReadVin = new ReadMessagesWorker();
         thReadVin.WorkerSupportsCancellation = true;
         thReadVin.WorkerReportsProgress = true;
         thReadVin.ProgressChanged += new System.ComponentModel.ProgressChangedEventHandler(this.thRead_ProgressChanged);
         thReadVin.RunWorkerAsync(MessVin);

//         messQ = new Queue<Msg>();
         messServiceL = new List<Msg>();
         messSyncL = new List<Msg>();
         messVinL = new List<Msg>();
      }

      private void timer1_Tick(object sender, EventArgs e)
      {
         cnt++;
         timer1.Stop();
         timer1.Start();
      }
      private void AddTotheList(Msg omsg)
      {
         int pos;
         string mt;  //use mt to keep the uppercase in original message.
         mt = omsg.message.ToLower();
         
         //pos = mt.IndexOf("count");
         //if (pos < 0)
         // pos = mt.IndexOf("cnt");

         //if (pos > 0)
         //{
         //   m = m.Substring(0, pos);
         //}
         //foreach (Msg msg1 in messQ)
         //{
         //   if (msg1.message == m)
         //   {
         //      msg1.cnt++;
         //      return;  //found likness in list add to the count.
         //   }

         //}
         Msg ms = new Msg();
         ms.message = omsg.message;
         ms.address = omsg.address;
         ms.cnt = 1;
         ms.msgDT = DateTime.Now;
         //messQ.Enqueue(ms);
         if (omsg.mtype == Msg.MessageType.service)
             messServiceL.Add(ms);
         else
             messSyncL.Add(ms);
          

      }
      private void ReBuildSyncScreenDataFromList()
      {
          rtbSync.Clear();
          int dqcnt;
          if (messSyncL.Count > MaxLines)
          {
              dqcnt = messSyncL.Count - TrimLines;
              messSyncL.RemoveRange(0, dqcnt);

          }
          for (int i = 0; i < messSyncL.Count - 1; i++)
          {
              tMess = messSyncL[i];
             // if (tMess.mtype == Msg.MessageType.service)
                  ScreenTheSyncData();
           //   else
              //    ScreenTheSyncData();
          }
      }
      private void ReBuildServiceScreenDataFromList()
      {
          rtbService.Clear();
          int dqcnt;
          if (messServiceL.Count > MaxLines)
          {
              dqcnt = messServiceL.Count - TrimLines;
              messServiceL.RemoveRange(0, dqcnt);

          }
          for (int i = 0; i < messServiceL.Count - 1; i++)
          {
              tMess = messServiceL[i];
             // if (tMess.mtype == Msg.MessageType.service)
             //     ScreenTheServiceData();
            //  else
                  ScreenTheServiceData();
          }
      }


      private void ScreenTheVinData()
      {
         
          string sdata = tMess.message;
          sdata += "   | {" + tMess.msgDT.ToShortTimeString().ToString() + "}  IP:" + tMess.address.ToString();

          cntService++;

          rtbVin.AppendText(sdata + "\r\n");
          if (rtbVin.Text.Length - (sdata.Length + 1) > 0)
              rtbVin.SelectionStart = rtbVin.Text.Length - (sdata.Length + 1);
          else
              rtbVin.SelectionStart = 0;
          rtbVin.SelectionLength = sdata.Length;
          rtbVin.SelectionColor = Color.Black;

          if (sdata.Contains("Complete"))
          {
              //Font f = rtbVin.SelectionFont;
              
              rtbVin.SelectionColor = Color.DarkViolet;
              //rtbVin.SelectionFont = Font.Size = 16;
          }
          if (sdata.Contains("Normal"))
              rtbVin.SelectionColor = Color.Blue;
          if (sdata.Contains("InitialLoad"))
              rtbVin.SelectionColor = Color.Green;
          if (sdata.Contains("Init"))
              rtbVin.SelectionColor = Color.Green;
          if (sdata.Contains("Start"))
              rtbVin.SelectionColor = Color.Green;
          if (sdata.Contains("Main"))
              rtbVin.SelectionColor = Color.DarkMagenta;
          if (sdata.Contains("Err:"))
              rtbVin.SelectionColor = Color.DarkRed;
          if (sdata.Contains("Error"))
              rtbVin.SelectionColor = Color.DarkRed;
          if (sdata.Contains("Count"))
              rtbVin.SelectionColor = Color.DarkSlateBlue;
          if (sdata.Contains("Info"))
              rtbVin.SelectionColor = Color.DarkGoldenrod;
          if (sdata.Contains("Data"))
              rtbVin.SelectionColor = Color.Black;
          rtbVin.SelectionStart = rtbVin.Text.Length - 1;
          rtbVin.SelectionLength = 0;

          rtbVin.ScrollToCaret();
          //if (cbSummary.Checked == true)
          //    ResetSummary();

      }

      private void ScreenTheServiceData()
      {
          if (cbStopCapService.Checked == true)
              return;

          string sdata = tMess.message;
          sdata += "    |{" + tMess.msgDT.ToShortTimeString().ToString() + "}  IP:" + tMess.address.ToString();
          
          cntService++;

          rtbService.AppendText(sdata + "\r\n");
          if (rtbService.Text.Length - (sdata.Length + 1) > 0)
              rtbService.SelectionStart = rtbService.Text.Length - (sdata.Length + 1);
          else
              rtbService.SelectionStart = 0;
          rtbService.SelectionLength = sdata.Length;
          rtbService.SelectionColor = Color.Black;

          if (sdata.Contains("Control Status"))
              rtbService.SelectionColor = Color.DarkViolet;
          if (sdata.Contains("Normal"))
              rtbService.SelectionColor = Color.Blue;
          if (sdata.Contains("InitialLoad"))
              rtbService.SelectionColor = Color.Green;
          if (sdata.Contains("Init"))
              rtbService.SelectionColor = Color.Green;
          if (sdata.Contains("Start"))
              rtbService.SelectionColor = Color.Green;
          if (sdata.Contains("End"))
              rtbService.SelectionColor = Color.DarkSeaGreen;
          if (sdata.Contains("Err:"))
              rtbService.SelectionColor = Color.DarkRed;
          if (sdata.Contains("Error"))
              rtbService.SelectionColor = Color.DarkRed;
          if (sdata.Contains("Count"))
              rtbService.SelectionColor = Color.DarkSlateBlue;
          rtbService.SelectionStart = rtbService.Text.Length - 1;
          rtbService.SelectionLength = 0;

          rtbService.ScrollToCaret();
          //if (cbSummary.Checked == true)
          //    ResetSummary();

      }
      int cntSync, cntService, cntVin;
      private void ScreenTheSyncData()
      {
          if (cbStopCapSync.Checked == true)
              return;

          string sdata = tMess.message;
          sdata += "    |{" + tMess.msgDT.ToShortTimeString().ToString() + "}  IP:" + tMess.address.ToString();

          cntSync++;

          rtbSync.AppendText(sdata + "\r\n");
          if (rtbSync.Text.Length - (sdata.Length + 1) > 0)
              rtbSync.SelectionStart = rtbSync.Text.Length - (sdata.Length + 1);
          else
              rtbSync.SelectionStart = 0;
          rtbSync.SelectionLength = sdata.Length;
          rtbSync.SelectionColor = Color.Black;

          if (sdata.Contains("Control Status"))
              rtbSync.SelectionColor = Color.DarkViolet;
          if (sdata.Contains("Normal"))
              rtbSync.SelectionColor = Color.Blue;
          if (sdata.Contains("InitialLoad"))
              rtbSync.SelectionColor = Color.Green;
          if (sdata.Contains("Init"))
              rtbSync.SelectionColor = Color.Green;
          if (sdata.Contains("Start"))
              rtbSync.SelectionColor = Color.Green;
          if (sdata.Contains("End"))
              rtbSync.SelectionColor = Color.DarkSeaGreen;
          if (sdata.Contains("Err:"))
              rtbSync.SelectionColor = Color.DarkRed;
          if (sdata.Contains("Error"))
              rtbSync.SelectionColor = Color.DarkRed;
          if (sdata.Contains("Count"))
              rtbSync.SelectionColor = Color.DarkSlateBlue;
          rtbSync.SelectionStart = rtbSync.Text.Length - 1;
          rtbSync.SelectionLength = 0;

          rtbSync.ScrollToCaret();
          //if (cbSummary.Checked == true)
          //    ResetSummary();

      }

      Msg tMess;
      private void thRead_ProgressChanged(object sender, ProgressChangedEventArgs e)
      {
          try
          {


              string[] mydata;
              tMess = (Msg)e.UserState;
              //lblCounter.Text = e.ProgressPercentage.ToString();
              
              AddTotheList(tMess);
              if (tMess.mtype == Msg.MessageType.vin)
                  ScreenTheVinData();
              else if (tMess.mtype == Msg.MessageType.service)
                  ScreenTheServiceData();
              else
                  ScreenTheSyncData();

              if (cbStartLogServices.Checked == true)
              {
                  if (tMess.mtype == Msg.MessageType.service)
                  {
                      if (fs1 == null)
                      {
                          string sTime;
                          sTime = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString();
                          sTime += DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString();
                          fs1 = new StreamWriter(label2.Text,true);
                          fs1.WriteLine(sTime);
                      }
                      fs1.WriteLine(tMess.msgDT + " - " + tMess.message);
                  }
                  if (tMess.mtype == Msg.MessageType.vin)
                  {
                      if (fs1 == null)
                      {
                          string sTime;
                          sTime = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString();
                          sTime += DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString();
                          fs1 = new StreamWriter(label2.Text, true);
                          fs1.WriteLine(sTime);
                      }
                      fs1.WriteLine(tMess.msgDT + " - " + tMess.message);
                  }

              }
              if (cbStartLogSync.Checked == true)
              {
                  if (tMess.mtype == Msg.MessageType.sync)
                  {
                      if (fs1 == null)
                      {
                          string sTime;
                          sTime = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString();
                          sTime += DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString();
                          fs1 = new StreamWriter(label2.Text,true);
                          fs1.WriteLine(sTime);
                      }
                      fs1.WriteLine(tMess.msgDT + " - " + tMess.message);
                  }
              }

              if (messServiceL.Count > MaxLines)
              {
                  ReBuildServiceScreenDataFromList();

              }
              if (messSyncL.Count > MaxLines)
              {
                  ReBuildSyncScreenDataFromList();
              }
          }
          catch (Exception exx)
          {
              MessageBox.Show(exx.Message);
          }
      }

      TextWriter fs1;

      //private void ResetSummary()
      //{
      //   rtbSummary.Clear();
      //   foreach (Msg msg in messL) 
      //   {
      //      if (msg.cnt > 1)
      //         rtbSummary.AppendText(msg.message + " - " + msg.cnt.ToString() + "\r\n");
      //   }
      //   rtbSummary.SelectionStart = rtbData.Text.Length - 1;
      //   rtbSummary.SelectionLength = 0;
      //   rtbSummary.ScrollToCaret();

      //}


      private void Form1_FormClosing(object sender, FormClosingEventArgs e)
      {
          


         thRead.CancelAsync();
         Application.DoEvents();
         UdpClient udpc = new UdpClient("127.0.0.1", 7782);
         string message = "End Process";
         udpc = new UdpClient("127.0.0.1", 7783);
         message = "End Process";
         byte[] bite = new byte[message.Length];
         int ii = 0;
         foreach (byte bt in message)
         {
            bite[ii] = bt;
            ii++;
         }
         udpc.Send(bite, bite.Length);
         //TimeSpan ts = new TimeSpan();
         //ts = TimeSpan.FromSeconds((long)30);
         //DateTime t1;
         //t1 = DateTime.Now;
         //while (thRead.IsBusy)
         //{
         //    if (DateTime.Now > t1 + ts)
         //    {

         //        thRead.Dispose();
         //        return;
         //    }
         //}
         //thRead.Dispose();
      }

      private void rtbSummary_TextChanged(object sender, EventArgs e)
      {

      }

      private void checkBox2_CheckedChanged(object sender, EventArgs e)
      {

      }

      private void checkBox3_CheckedChanged(object sender, EventArgs e)
      {

      }

      private void button1_Click(object sender, EventArgs e)
      {
          WriteUDPMessage("begin");
      }
      public static void WriteUDPMessageProd(string message)
      {
          string MachineName = "local";
          //message = message += 249 + MachineName;
          UdpClient udpc = new UdpClient("10.9.10.15", 7780);
          byte[] bite = new byte[message.Length + MachineName.Length + 1];
          int ii = 0;
          foreach (byte bt in message)
          {
              bite[ii] = bt;
              ii++;
          }
          bite[ii] = 249;
          ii++;
          foreach (byte bt in MachineName)
          {
              bite[ii] = bt;
              ii++;
          }

          udpc.Send(bite, bite.Length);

      }

      public static void WriteUDPMessage(string message)
      {
          
          string MachineName = "local";
          //message = message += 249 + MachineName;
          WriteMessageDebug("sending message 'begin' to 7780", "server");
          UdpClient udpc = new UdpClient("10.15.82.210", 7780);
          byte[] bite = new byte[message.Length + MachineName.Length + 1];
          int ii = 0;
          foreach (byte bt in message)
          {
              bite[ii] = bt;
              ii++;
          }
          bite[ii] = 249;
          ii++;
          foreach (byte bt in MachineName)
          {
              bite[ii] = bt;
              ii++;
          }

          udpc.Send(bite, bite.Length);

      }
      public static void WriteMessageDebug(string message, string MachineName)
      {

          //message = message += 249 + MachineName;

          UdpClient udpc = new UdpClient("10.15.82.210", 7784);
          byte[] bite = new byte[message.Length + MachineName.Length + 3];
          int ii = 0;
          foreach (byte bt in message)
          {
              bite[ii] = bt;
              ii++;
          }
          bite[ii] = 32;
          ii++;
          bite[ii] = 64;
          ii++;
          bite[ii] = 32;
          ii++;

          foreach (byte bt in MachineName)
          {
              bite[ii] = bt;
              ii++;
          }

          udpc.Send(bite, bite.Length);

      }
      public static void WriteMessageDebugOld(string message, string MachineName)
      {

          //message = message += 249 + MachineName;

          UdpClient udpc = new UdpClient("127.0.0.1", 7783);
          byte[] bite = new byte[message.Length + MachineName.Length + 1];
          int ii = 0;
          foreach (byte bt in message)
          {
              bite[ii] = bt;
              ii++;
          }
          bite[ii] = 249;
          ii++;
          foreach (byte bt in MachineName)
          {
              bite[ii] = bt;
              ii++;
          }

          udpc.Send(bite, bite.Length);

      }

      private void button2_Click(object sender, EventArgs e)
      {
          WriteUDPMessageProd("begin");
      }
   }
}